<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px; display: flex; gap: 10px;">
      <el-input
        v-model="searchUsername"
        placeholder="搜索用户名"
        clearable
        style="width: 300px"
        @clear="getUserList"
      />
      <el-button type="primary" @click="getUserList">搜索</el-button>
      <el-button type="success" @click="openDialog()">新增用户</el-button>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userList" border style="width: 100%">
      <el-table-column label="用户名" prop="username" align="center" />
      <el-table-column label="角色" prop="role" align="center" />
      <el-table-column label="备注" prop="introduction" align="center" min-width="80" />
      <el-table-column label="权限" align="center" min-width="100">
        <template slot-scope="{ row }">
          <div v-if="row.apipermissions && Object.values(row.apipermissions).includes(true)">
            <el-tag
              v-for="key in permissionKeys"
              v-if="row.apipermissions[key]"
              :key="key"
              type="success"
              size="mini"
              style="margin: 2px"
            >
              {{ permissionLabels[key] }}
            </el-tag>
          </div>
          <div v-else>
            <el-tag type="info" size="mini">无权限</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120">
        <template slot-scope="{ row }">
          <el-button size="mini" @click="openDialog(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.username)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗表单 -->
    <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" :visible.sync="dialogVisible">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" placeholder="不修改可留空" show-password />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="admin" value="admin" />
            <el-option label="manager" value="manager" />
            <el-option label="operator" value="operator" />
            <el-option label="advertiser" value="advertiser" />
            <el-option label="user" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-checkbox-group v-model="activePermissions">
            <el-checkbox v-for="key in permissionKeys" :key="key" :label="key">
              {{ permissionLabels[key] }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, updateUser, deleteUser, register } from '@/api/user'

export default {
  name: 'UserManagement',
  data() {
    return {
      searchUsername: '',
      userList: [],
      dialogVisible: false,
      isEdit: false,
      form: {
        username: '',
        password: '',
        role: '',
        apipermissions: {},
        introduction: ''
      },
      permissionLabels: {
        viewLogs: '查看日志',
        viewConfigs: '查看配置',
        originPush: '初始推送',
        batchPush: '批量推送',
        addAd: '添加广告',
        addHeader: '添加 Header',
        UploadPixelID: '上传 PixelID',
        destroySite: '销毁站点',
        batchDestroy: '批量销毁',
        defaultconfig: '添加默认配置'
      },
      permissionKeys: [
        'viewLogs',
        'viewConfigs',
        'originPush',
        'batchPush',
        'addAd',
        'addHeader',
        'UploadPixelID',
        'destroySite',
        'batchDestroy',
        'defaultconfig'
      ]
    }
  },
  computed: {
    activePermissions: {
      get() {
        return Object.keys(this.form.apipermissions).filter(key => this.form.apipermissions[key])
      },
      set(newKeys) {
        const result = {}
        for (const key of this.permissionKeys) {
          result[key] = newKeys.includes(key)
        }
        this.form.apipermissions = result
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data } = await getUsers(this.searchUsername ? { username: this.searchUsername } : {})
      this.userList = data || []
    },
    openDialog(row = null) {
      this.dialogVisible = true
      this.isEdit = !!row
      if (row) {
        this.form = {
          username: row.username,
          password: '',
          role: row.role,
          apipermissions: { ...this.defaultPermissions(), ...row.apipermissions },
          introduction: row.introduction || ''
        }
      } else {
        this.form = {
          username: '',
          password: '',
          role: 'user',
          apipermissions: this.defaultPermissions(),
          introduction: ''
        }
      }
    },
    defaultPermissions() {
      const result = {}
      for (const key of this.permissionKeys) {
        result[key] = false
      }
      return result
    },
    async handleSave() {
      const payload = {
        role: this.form.role,
        apipermissions: this.form.apipermissions,
        introduction: this.form.introduction,
        ...(this.form.password ? { password: this.form.password } : {})
      }

      if (this.isEdit) {
        await updateUser(this.form.username, payload)
      } else {
        await register({
          username: this.form.username,
          password: this.form.password,
          role: this.form.role,
          apipermissions: this.form.apipermissions,
          introduction: this.form.introduction
        })
      }

      this.dialogVisible = false
      this.getUserList()
    },
    async handleDelete(username) {
      this.$confirm(`确定要删除用户：${username} 吗？`, '提示', {
        type: 'warning'
      }).then(async() => {
        await deleteUser(username)
        this.getUserList()
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
